package com.launcher.factory;

import java.util.ArrayList;
import java.util.List;

import com.launcher.PayLoad;
import com.launcher.Rocket;
import com.launcher.RocketService;
import com.launcher.decorator.Engine;
import com.launcher.decorator.IEngine;
import com.launcher.decorator.IFairring;
import com.launcher.decorator.IStage;

public abstract class RocketFactory
{
	protected RocketFactory() {}

	public abstract Rocket createRocket(PayLoad payload);
	
	public abstract IFairring createFairring(int cost, int mass, int capability);
	
	public abstract IEngine createEngine(int cost, int power);
	
	public abstract IStage createStage(int cost, int mass, int height);

	public PayLoad createPayLoad(int cost, int mass, int height)
	{
		PayLoad payload = new PayLoad();
		payload.setCost(cost);
		payload.setMass(mass);
		payload.setHeight(height);
		
		RocketService.getInstance().savePayLoad(payload);
		
		return payload;
	}
	
	protected List<Engine> getCheapestEngineCombination(List<Engine> engines, List<Engine> remaining, int power, int mass)
	{
		List<Engine> list = new ArrayList<Engine>();
		for (Engine l : engines)
		{
			list.add(l);
		}
		
		List<Engine> best = new ArrayList<Engine>();
		
		if (power < mass)
		{
			for (Engine e : remaining)
			{
				if (!list.contains(e))
				{
					list = new ArrayList<Engine>();
					for (Engine l : engines)
					{
						list.add(l);
					}
					list.add(e);
					
					List<Engine> newRemaining = new ArrayList<Engine>();
					for (Engine l : remaining)
					{
						newRemaining.add(l);
					}
					newRemaining.remove(e);
					
					List<Engine> temp = getCheapestEngineCombination(list, newRemaining, power + e.getPower(), mass + e.getMass() + e.getRocketDecorator().getMass());
					
					int bestCost = 0;
					for (Engine engine : best)
					{
						bestCost += engine.getCost() + engine.getRocketDecorator().getCost();
					}
					
					int tempCost = 0;
					for (Engine engine : temp)
					{
						tempCost += engine.getCost() + engine.getRocketDecorator().getCost();
					}
					
					if (tempCost <= bestCost || bestCost == 0)
					{
						best = new ArrayList<Engine>();
						for (Engine t : temp)
						{
							best.add(t);
						}
					}
				}
			}
		}
		else
		{
			for (Engine l : engines)
			{
				best.add(l);
			}
		}
		
		return best;
	}
}
